export default class emitter {
    // static _callbacks: any;
    /**
    返回监听事件的个数
    */
    static hasListeners(event) {
        return !!this.listeners(event).length;
    };

    /**
    返回所有监听事件
    */
    static listeners(event) {
        //@ts-ignore
        this._callbacks = this._callbacks || {};
        //@ts-ignore
        return this._callbacks[event] || [];
    };

    /**
    发送事件，当发送该事件时会触发相应的监听的回调函数
    */
    static emit(event, ...agrs) {
        //@ts-ignore
        this._callbacks = this._callbacks || {};
        var args = [].slice.call(arguments, 1);
        //@ts-ignore
        var callbacks = this._callbacks[event];

        if (callbacks) {
            callbacks = callbacks.slice(0);
            for (var i = 0, len = callbacks.length; i < len; ++i) {
                callbacks[i].apply(this, args);
            }
        }
        return this;
    };

    // Emitter.prototype.removeEventListener =
    // Emitter.prototype.removeListener =
    // Emitter.prototype.removeAllListeners =
    /**
    移除监听事件，当不传参数时，所有事件都会被移除
    */
    static off(event, fn) {
        //@ts-ignore
        this._callbacks = this._callbacks || {};

        // all
        if (0 == arguments.length) {
            //@ts-ignore
            this._callbacks = {};
            return this;
        }

        // specific event
        //@ts-ignore
        var callbacks = this._callbacks[event];
        if (!callbacks) return this;

        // remove all handlers
        if (1 == arguments.length) {
            //@ts-ignore
            delete this._callbacks[event];
            return this;
        }

        // remove specific handler
        var cb;
        for (var i = 0; i < callbacks.length; i++) {
            cb = callbacks[i];
            if (cb === fn || cb.fn === fn) {
                callbacks.splice(i, 1);
                break;
            }
        }
        return this;
    };

    /**
    添加事件，该事件只被触发一次，触发后会被移除
    */
    static once(event, fn) {
        var self = this;
        //@ts-ignore
        this._callbacks = this._callbacks || {};

        function on() {
            self.off(event, on);
            fn.apply(this, arguments);
        }

        on.fn = fn;
        this.on(event, on);
        return this;
    };

    /**
    添加监听事件
    */
    static on(event, fn) {
        //@ts-ignore
        this._callbacks = this._callbacks || {};
        //@ts-ignore
        (this._callbacks[event] = this._callbacks[event] || [])
            .push(fn);
        return this;
    };
}